package meijuli.com.join51.business.message;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.FrameLayout;

import meijuli.com.join51.business.R;
import meijuli.com.join51.business.adapter.CustomAdapter;
import meijuli.com.join51.business.adapter.CustomHolder;
import meijuli.com.join51.business.fragment.BaseFragment;
import meijuli.com.join51.business.model.Announcement;
import meijuli.com.join51.business.model.Message;
import com.jhx.common.model.User;
import meijuli.com.join51.business.ui.LoadFooterView;
import meijuli.com.join51.business.ui.RefreshHeaderView;
import meijuli.com.join51.business.utils.TimeUtil;
import com.jhx.common.utils.UserManager;
import com.liaoinstan.springview.widget.SpringView;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息页面
 *
 * @author jack 2017-05-12 18:56
 */
public class MessageFragment extends BaseFragment implements Contract.MessageView {
    SpringView mSpringView;
    RecyclerView mRecyclerView;
    ViewStub mViewStub;
    FrameLayout mContentViewLayout;
    //公告
    public static final int ANNOUNCEMENT = 1;
    //消息
    public static final int MESSAGE = 2;
    public static final String KEY_TYPE = "type";
    private MessagePresenterImpl mMessagePresenter;
    private CustomAdapter<Message> mMessageAdapter;
    private CustomAdapter<Announcement> mAnnouncementAdapter;
    private List<Message> mMessageList;
    private List<Announcement> mAnnouncementList;
    private boolean isRefresh = true;
    private int pageIndex = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_message, container, false);
        mSpringView = view.findViewById(R.id.springview);
        mRecyclerView = view.findViewById(R.id.recyclerview_message);
        mViewStub = view.findViewById(R.id.viewstub_empty);
        mContentViewLayout = view.findViewById(R.id.ll_content_view);
        return view;
    }

    public static MessageFragment newInstance(int type) {
        MessageFragment fragment = new MessageFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(KEY_TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        final int type = getArguments().getInt(KEY_TYPE);
        final User user = UserManager.get().getUser();
        if (UserManager.get().checkUserNull(mActivity)) {
            return;
        }
        mMessageList = new ArrayList<>();
        mAnnouncementList = new ArrayList<>();
        mSpringView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                pageIndex = 1;
                isRefresh = true;
                if (type == ANNOUNCEMENT) {
                    mMessagePresenter.loadAnnouncement(pageIndex, user.getDmId() + "", false);
                } else {
                    mMessagePresenter.loadMessage(pageIndex, user.getDmId() + "", false);
                }
            }

            @Override
            public void onLoadmore() {
                isRefresh = false;
                if (type == ANNOUNCEMENT) {
                    mMessagePresenter.loadAnnouncement(pageIndex, user.getDmId() + "", false);
                } else {
                    mMessagePresenter.loadMessage(pageIndex, user.getDmId() + "", false);
                }
            }
        });
        mMessagePresenter = new MessagePresenterImpl(this, getActivity());
        if (type == ANNOUNCEMENT) {
            mMessagePresenter.loadAnnouncement(pageIndex, user.getDmId() + "", true);
        } else {
            mMessagePresenter.loadMessage(pageIndex, user.getDmId() + "", true);
        }
        mSpringView.setHeader(new RefreshHeaderView(getActivity()));
        mSpringView.setFooter(new LoadFooterView(getActivity()));
    }

    private void displayLoadingView(boolean display) {
        for (int i = 0; i < mContentViewLayout.getChildCount(); i++) {
            View childView = mContentViewLayout.getChildAt(i);
            if (R.id.fl_progress_bar == childView.getId()) {
                childView.setVisibility(display ? View.VISIBLE : View.GONE);
            } else {
                childView.setVisibility(display ? View.GONE : View.VISIBLE);
            }
        }
    }

    @Override
    public void beforeLoad() {
        displayLoadingView(true);
    }

    @Override
    public void afterLoad() {
        displayLoadingView(false);
    }

    @Override
    public void loadError() {
        mSpringView.onFinishFreshAndLoad();
    }

    @Override
    public void loadMessage(List<Message> messageList) {
        mSpringView.onFinishFreshAndLoad();
        pageIndex++;
        if (messageList != null) {
            if (isRefresh) {
                mMessageList.clear();
            }
            mMessageList.addAll(messageList);
            if (mMessageAdapter == null) {
                mMessageAdapter = new CustomAdapter<Message>(mMessageList,
                        getActivity(), R.layout.item_message, null) {
                    @Override
                    public void onBindData(CustomHolder holder, int position, Message message) {
                        holder.setText(R.id.text_title, message.getTitle());
                        holder.setText(R.id.text_time, TimeUtil.getFormatTime(Long.parseLong(message.getCrtime()),
                                "yyyy-MM-dd HH:mm:ss"));
                        holder.setText(R.id.text_message, message.getMassge());
                    }
                };
                mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                mRecyclerView.setAdapter(mMessageAdapter);
            } else {
                mMessageAdapter.updateView(mMessageList);
            }
        } else {
            if (isRefresh) {
                mViewStub.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void loadAnnouncement(ArrayList<Announcement> announcementList) {
        mSpringView.onFinishFreshAndLoad();
        if (mAnnouncementList != null) {
            if (isRefresh) {
                mAnnouncementList.clear();
            }
            mAnnouncementList.addAll(announcementList);
            if (mAnnouncementAdapter == null) {
                mAnnouncementAdapter = new CustomAdapter<Announcement>(mAnnouncementList,
                        getActivity(), R.layout.item_message, null) {
                    @Override
                    public void onBindData(CustomHolder holder, int position, Announcement announcement) {
                        holder.setText(R.id.text_title, announcement.getTitle());
                        holder.setText(R.id.text_time, TimeUtil.getFormatTime(announcement.getCreateTime(),
                                "yyyy-MM-dd hh:mm:ss"));
                        holder.setText(R.id.text_message, announcement.getContent());
                    }
                };
                mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                mRecyclerView.setAdapter(mAnnouncementAdapter);
            } else {
                mAnnouncementAdapter.updateView(mAnnouncementList);
            }
        } else {
            if (isRefresh) {
                mViewStub.setVisibility(View.VISIBLE);
            }
        }
    }
}
